#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <sys/time.h>
#include <input_manager.h>

static int stdinDevInit(void);
static int stdinDevExit(void);
static int stdinGetInputEvent(PT_inputEvent g_ptInputEvent);

static T_inputOpr stdInputOpr=
{
	.name 				= "stdin",
	.inputDeviceInit 	= stdinDevInit,
	.inputDeviceExit 	= stdinDevExit,
	.getInputEvent 		= stdinGetInputEvent,
	.next				= NULL,
};

static int stdinDevInit(void)
{
    struct termios tTTYState;
 
    //get the terminal state
    tcgetattr(STDIN_FILENO, &tTTYState);
 
    //turn off canonical mode
    tTTYState.c_lflag &= ~ICANON;
    //minimum of number input read.
    tTTYState.c_cc[VMIN] = 1;

    //set the terminal attributes.
    tcsetattr(STDIN_FILENO, TCSANOW, &tTTYState);

	return 0;
}

static int stdinDevExit(void)
{

    struct termios tTTYState;
 
    //get the terminal state
    tcgetattr(STDIN_FILENO, &tTTYState);
 
    //turn on canonical mode
    tTTYState.c_lflag |= ICANON;
	
    //set the terminal attributes.
    tcsetattr(STDIN_FILENO, TCSANOW, &tTTYState);	
	return 0;
}

static int stdinGetInputEvent(PT_inputEvent g_ptInputEvent)
{
	char c;
	g_ptInputEvent->type = INPUT_TYPE_STDIN;
	g_ptInputEvent->x = -1;
	g_ptInputEvent->y = -1;
	g_ptInputEvent->pressed = -1;

	c = fgetc(stdin);
	gettimeofday(&g_ptInputEvent->time,NULL);

	switch(c)
	{
		case 'u':
			g_ptInputEvent->value = INPUT_VALUE_UP;
			break;
		case 'n':
			g_ptInputEvent->value = INPUT_VALUE_DOWN;
			break;
		case 'q':
			g_ptInputEvent->value = INPUT_VALUE_EXIT;
			break;
		default:
			g_ptInputEvent->value = INPUT_VALUE_UNOKWN;
			break;
	}
	
	return 0;
}

int stdinInit(void)
{
	int ret;

	ret = registerInputOpr(&stdInputOpr);
	return ret;
}

